package actions;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import db.dao.Users;
import db.dao.UsersDAO;
/*登录action*/
public class LoginAction extends ActionSupport{

	private String loginName="";	//用户名
	private String loginPwd="";	//密码
	
	public LoginAction() {
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getLoginPwd() {
		return loginPwd;
	}

	public void setLoginPwd(String loginPwd) {
		this.loginPwd = loginPwd;
	}
	
	public String execute() throws IOException {
		//获取页面信息，用于弹窗提示和清除页面缓存
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		//查找用户
		UsersDAO udao=new UsersDAO();
		Users users=udao.findById(loginName);
		//判空并判断密码正确
		if ((users!=null)&&(loginPwd.equals(users.getUserpwd()))) {
			session.setAttribute("username", loginName);
			session.setAttribute("usertype", users.getUsertype());
			//判断用户性质决定跳转页面
			if (users.getUsertype().equals("学生")) {
				return "student";
			}else if (users.getUsertype().equals("教师")) {
				return "teacher";
			}else if (users.getUsertype().equals("管理")) {
				return "manager";
			}
			return null;
		}else {
			//失败弹窗提示
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter printWriter = response.getWriter();
            printWriter.print("<script>alert('用户名或密码错误!')</script>");
            printWriter.print("<script>window.location.href='/GroupProject/index.jsp'</script>");
            printWriter.flush();
            printWriter.close();
            response.setHeader("Pragma","No-cache");   
            response.setHeader("Cache-Control","no-cache");  
            response.setHeader("Cache-Control", "no-store");  
            response.setDateHeader("Expires", 0);
			return null;
		}
	}
}
